<template>
    <div class="content">
        <div class="language-bar">
            <!--<span @click="languageChange('en')">{{ld.frame.languageTypeEN[languageType]}}</span> |
            <span @click="languageChange('jp')">{{ld.frame.languageTypeJP[languageType]}}</span> |
            <span @click="languageChange('ko')">{{ld.frame.languageTypeKO[languageType]}}</span>-->
            <span @click="languageChange('en')">English</span> |
            <span @click="languageChange('jp')">日本語</span> |
            <span @click="languageChange('ko')">한국어</span>
        </div>
        <van-form colon @submit="onSubmit" validate-first @failed="onFailed">
            <div class="title">{{ld.frame.title1[languageType]}}</div>
            <van-field
                    v-model="formItem.name"
                    name="name"
                    :label="ld.tip.name.label[languageType]"
                    :placeholder="ld.tip.name.ph[languageType]"
                    :maxlength="50"
                    @focus="bodyScrollTop"
                    @blur="bodyScrollTop"></van-field>
            <van-field
                    v-model="formItem.relation"
                    name="relation"
                    :label="ld.tip.relation.label[languageType]"
                    :placeholder="ld.tip.relation.ph[languageType]"
                    @blur="bodyScrollTop"
                    @focus="bodyScrollTop"></van-field>
            <van-field
                    :label="ld.tip.sex.label[languageType]"
            >
                <template #input>
                    <van-radio-group v-model="formItem.sex" direction="horizontal">
                        <van-radio name="男" icon-size="22px">{{ld.tip.sex.val1[languageType]}}</van-radio>
                        <van-radio name="女" icon-size="22px">{{ld.tip.sex.val2[languageType]}}</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field
                    v-model="formItem.age"
                    name="age"
                    :label="ld.tip.age.label[languageType]"
                    @blur="bodyScrollTop"
                    @focus="bodyScrollTop"
                    :placeholder="ld.tip.age.ph[languageType]"
            />

            <!--<van-field
                    v-model="formItem.is_permanent"
                    name="nationality"
                    :label="ld.tip.nationality.label[languageType]"
                    @blur="bodyScrollTop"
                    @focus="bodyScrollTop"
                    :placeholder="ld.tip.nationality.ph[languageType]"
            />-->

            <van-field
                    readonly
                    clickable
                    name="nationality"
                    :value="formItem.is_permanent_name"
                    :label="ld.tip.nationality.label[languageType]"
                    :placeholder="ld.tip.nationality.ph1[languageType]"
                    @click="showNationality = true"
            />

            <van-popup v-model="showNationality" position="bottom">
                <van-picker show-toolbar
                            :confirm-button-text="ld.tip.nationality.confirm[languageType]"
                            :cancel-button-text="ld.tip.nationality.cancel[languageType]"
                            :title="ld.tip.nationality.title[languageType]"
                            @cancel="showNationality=false"
                            @confirm="nationalityConfirm"
                            :columns="getNationalityData"/>
            </van-popup>

            <van-field
                    v-model="formItem.card_no"
                    name="card_no"
                    :label="ld.tip.cardno.label[languageType]"
                    @blur="bodyScrollTop"
                    @focus="bodyScrollTop"
                    :placeholder="ld.tip.cardno.ph[languageType]"
            />
            <van-field
                    v-model="formItem.tel"
                    name="tel"
                    :label="ld.tip.tel.label[languageType]"
                    :placeholder="ld.tip.tel.ph[languageType]"
                    @focus="bodyScrollTop"
                    @blur="validatePhoneAction"/>
            <area-page ref="areaPage" :language-type="languageType" @result="bodyScrollTop"></area-page>
            <div class="title">{{ld.frame.title2[languageType]}}</div>
            <recent-situation ref="recentSituation" :language-type="languageType"
                              @result="bodyScrollTop"></recent-situation>

            <div class="div-bot">
                <van-button :disabled="submitDisabled" :loading="submitLoading" round block type="info"
                            native-type="submit" class="city-card-common-btn">
                    {{ld.frame.submit[languageType]}}
                </van-button>
            </div>
        </van-form>
        <!-- 审核提示-->
        <van-popup class="readme-popup" v-model="examineModel" :close-on-click-overlay="false" safe-area-inset-bottom
                   :style="{ width: '80%', position: 'fixed', top: '50%', borderRadius: '10px' }">
            <div class="readme-popup-title">{{ld.frame.warmTip.title[languageType]}}</div>
            <div class="language-bar-mini">
                <span @click="languageChange('en')">English</span> |
                <span @click="languageChange('jp')">日本語</span> |
                <span @click="languageChange('ko')">한국어</span>
            </div>
            <div class="readme-popup-content">
                <p>{{language.successAlertNow[this.languageType]}}({{formItem.card_no}})</p>
            </div>
            <div class="readme-popup-btn">
                <van-button block type="info"
                            native-type="button"
                            size="small"
                            class="readme-popup-btn-sm"
                            @click="examineCloseAction">
                    {{ld.frame.warmTip.btnClose[languageType]}}
                </van-button>
            </div>
        </van-popup>
        <!-- 公众号二维码-->
        <van-popup v-model="successModel" :close-on-click-overlay="false" safe-area-inset-bottom
                   :style="{ width: '80%', position: 'fixed', top: '50%', borderRadius: '10px' }">
            <div class="success-title">
                <div>{{ld.frame.qrcode.title[languageType]}}</div>
            </div>
            <div class="success-code">
                <img :src="require('@/assets/images/waiji.png')"/>
            </div>
        </van-popup>
        <!--    提示说明    -->
        <van-popup v-model="showReadme" :close-on-click-overlay="false" safe-area-inset-bottom
                   :style="{ width: '80%', position: 'fixed', top: '50%', borderRadius: '10px' }">
            <div class="readme-popup">
                <div class="readme-popup-title">{{ld.frame.warmTip.title[languageType]}}</div>
                <div class="language-bar-mini">
                    <!--<span @click="languageChange('en')">{{ld.frame.languageTypeEN[languageType]}}</span> |
                    <span @click="languageChange('jp')">{{ld.frame.languageTypeJP[languageType]}}</span> |
                    <span @click="languageChange('ko')">{{ld.frame.languageTypeKO[languageType]}}</span>-->
                    <span @click="languageChange('en')">English</span> |
                    <span @click="languageChange('jp')">日本語</span> |
                    <span @click="languageChange('ko')">한국어</span>
                </div>
                <div class="readme-popup-content">
                    <p>{{ld.frame.warmTip.content1[languageType]}}</p>
                    <p>{{ld.frame.warmTip.content2[languageType]}}</p>
                    <div class="tong-yi-box">
                        <van-checkbox v-model="tongyi" style="float: left;margin: 0px 8px;"></van-checkbox>
                        <div>{{ld.frame.warmTip.accept[languageType]}}</div>
                    </div>
                </div>
                <div class="readme-popup-btn">
                    <van-button block type="info"
                                native-type="button"
                                size="small"
                                class="readme-popup-btn-sm"
                                @click="choose">
                        {{ld.frame.warmTip.btn[languageType]}}
                    </van-button>
                </div>
            </div>

        </van-popup>

    </div>
</template>

<script>
import { insertNewPermitPerson, insertNewPermitChildren, getOpenidMsg } from '@/api/yi-qing-fang-kong.js'
// 工具
import { identityCodeValid, identityMobile } from '@/libs/tools'
import AreaPage from './wai-ji-components/area-page/index'
import RecentSituation from './wai-ji-components/recent-situation/index'
// import wx from 'weixin-js-sdk'
import dist from '@/libs/dist'
import languageDist from '@/libs/languageDist'
import guoji from '@/libs/guoji'

export default {
  components: {
    RecentSituation,
    AreaPage
  },
  data () {
    // this.phoneRules = [
    //   { required: true, message: this.ld.tip.tel.msg2[this.languageType] },
    //   { validator: this.phoneValidator, message: this.ld.tip.tel.msg3[this.languageType] }
    // ]
    return {
      guojiData: guoji,
      addType: '',
      formItem: {
        // 表单数据
        is_permanent_name: '',
        name: '',
        card_no: '',
        tel: '',
        area_type: '', // 区域类型
        area_id: '',
        street_id: '',
        community_id: '',
        area: '',
        street: '',
        community: '',
        loc_province: '', // 地图选取后的省
        loc_city: '', // 地图选取后的市
        loc_title: '', // 地图选取后的地址名
        loc_address: '', // 地图选取后的具体地址
        house_num: '', // 门牌号
        is_hubei: '',
        is_contact: '',
        health_state: '',
        temp: ''
      },
      sendBtnType: false,
      showReadme: true,
      tongyi: true,
      submitDisabled: false,
      submitLoading: false,
      successModel: false,
      examineModel: false,
      showNationality: false,
      routeObj: {}, // 路由对象
      language: dist.language,
      languageType: 0,
      ld: languageDist,
      nationalityData: []
    }
  },
  computed: {
    getNationalityData () {
      let newNationalityList = []
      this.nationalityData.forEach(item => {
        let obj = {}
        switch (this.languageType) {
          case 0:
            obj.text = item.EN
            break
          case 1:
            obj.text = item.JP
            break
          case 2:
            obj.text = item.KR
            break
        }
        obj.id = item.id
        newNationalityList.push(obj)
      })
      return newNationalityList
    }
  },
  methods: {
    failNotice (title) {
      this.$notify({ type: 'danger', message: title })
    },
    idCardValidator (val) {
      // 身份证
      const reg1 = identityCodeValid(val)
      if (!reg1.pass) {
        // this.failNotice('请检查身份证格式！')
        return false
      }
    },
    validatePhoneAction () {
      this.bodyScrollTop()
      if (!identityMobile(this.formItem.tel)) {
        this.failNotice(this.ld.tip.tel.msg3[this.languageType])
      }
    },
    // phoneValidator (val) {
    //   return identityMobile(val)
    // },
    // nameValidator (val) {
    //   if (val === '') {
    //     this.failNotice(this.ld.tip.name.msg[this.languageType])
    //     return false
    //   }
    //   return true
    // },
    // cardTypeValidator (val) {
    //   if (val === '') {
    //     this.failNotice('请选择证件类型')
    //     return false
    //   }
    //   return true
    // },
    onFailed (errorInfo) {
      this.failNotice(errorInfo.errors[0].message)
      console.log('failed', errorInfo)
    },
    onSubmit (value) {
      console.log('表单提交', this.formItem)
      // 校验姓名
      if (!this.formItem.name) {
        this.failNotice(this.ld.tip.name.msg[this.languageType])
        return false
      }
      if (!this.formItem.relation) {
        this.failNotice(this.ld.tip.relation.msg[this.languageType])
        return false
      }
      if (!this.formItem.sex) {
        this.failNotice(this.ld.tip.sex.msg[this.languageType])
        return false
      }
      if (!this.formItem.age) {
        this.failNotice(this.ld.tip.age.msg[this.languageType])
        return false
      }
      if (!this.formItem.is_permanent) {
        this.failNotice(this.ld.tip.nationality.msg1[this.languageType])
        return false
      }
      if (!this.formItem.card_no) {
        this.failNotice(this.ld.tip.cardno.msg[this.languageType])
        return false
      } else {
        if (this.formItem.card_no.length < 6) {
          this.failNotice(this.ld.tip.cardno.msg[this.languageType])
          return false
        }
      }

      // 校验证件号
      // if (!this.formItem.card_no) {
      //   this.failNotice('Please fill in passport number.')
      //   return false
      // } else {
      //   const rtn = identityCodeValid(this.formItem.card_no)
      //   // console.log('身份证校验原因', rtn.tip)
      //   // console.log('身份证校验状态', rtn.pass)
      //   if (!rtn.pass) {
      //     this.failNotice(rtn.tip)
      //     return false
      //   }
      // }
      // 校验手机号
      if (!identityMobile(this.formItem.tel)) {
        this.failNotice(this.ld.tip.tel.msg[this.languageType])
        return false
      }
      // 区域部分
      const areaPageData = this.$refs.areaPage.checkForm()

      // 近期情况
      const recentSituationData = this.$refs.recentSituation.checkForm()

      // 姓名去空格处理
      this.formItem.name = this.formItem.name.toString().replace(/\s/ig, '')
      // 手机号去空格处理
      this.formItem.tel = this.formItem.tel.toString().trim()
      // 身份证去空格处理
      this.formItem.card_no = this.formItem.card_no.toString().trim()

      if (this.formItem.tel.length !== 11) {
        this.failNotice('请输入正确手机号')
        return false
      } else {
        console.log(this.formItem.tel, '手机位数为：' + this.formItem.tel.length)
      }

      console.log('区域组件', areaPageData)
      console.log('近期情况组件', recentSituationData)
      if (areaPageData && recentSituationData) {
        // 组件数据处理
        this.formItem.area_type = areaPageData.area_type
        this.formItem.area_id = areaPageData.area.id
        this.formItem.area = areaPageData.area.text
        this.formItem.street_id = areaPageData.street.id
        this.formItem.street = areaPageData.street.text
        this.formItem.community_id = areaPageData.community.id
        this.formItem.company_code = !this.$common.xeUtils.isEmpty(areaPageData.community.company_code) ? areaPageData.community.company_code : areaPageData.street.company_code
        this.formItem.community = areaPageData.area_type === '1' ? areaPageData.community.text : areaPageData.cunValue
        this.formItem.house_num = areaPageData.house_num
        // this.formItem.loc_title = areaPageData.title
        this.formItem.loc_address = areaPageData.address
        this.formItem.loc_title = areaPageData.address
        this.formItem.address = areaPageData.address
        this.formItem.loc_province = areaPageData.province
        this.formItem.loc_city = areaPageData.city
        this.formItem.longitude = areaPageData.lng
        this.formItem.latitude = areaPageData.lat
        // this.formItem.address = this.formItem.loc_province + this.formItem.loc_city + this.formItem.loc_title + this.formItem.loc_address
        // this.formItem.is_hubei = recentSituationData.is_hubei
        this.formItem.is_contact = recentSituationData.is_contact
        this.formItem.health_state = recentSituationData.health_state_copy.join('^')
        this.formItem.health_state.replace(/,/g, '^')
        this.formItem.temp = recentSituationData.temp
        this.formItem.stay_city = recentSituationData.stay_city
        if (this.addType === '0') {
          this.formItem.p1 = 'children'
        }
        if (this.addType === '1') {
          this.formItem.p1 = 'person'
        }
        // 校验成功后插入
        console.log('校验成功-进开始行插入', this.formItem)
        this.insertCountrypermitAction()
      }
    },
    // 表单提交
    insertCountrypermitAction () {
      console.log('表单最终提交内容', this.formItem)
      // 表单提交
      this.successModel = false
      this.submitDisabled = false
      this.submitLoading = true
      if (this.addType === '0') {
        insertNewPermitChildren(this.formItem).then(ret => {
          if (ret.data.errcode === 0) {
            this.submitDisabled = true
            this.submitLoading = false
            console.log('保存回调', ret.data.data)
            window.localStorage.removeItem('formData')
            if (this.$route.query.selfTs === 'selfTs') {
              this.$dialog.alert({
                title: this.ld.frame.success.title[this.languageType],
                message: this.ld.frame.success.msg[this.languageType]
              }).then(() => {
                this.$router.push({
                  name: 'epidemic-newly-added-waiji-list',
                  query: {
                    newlyAddedType: '1'
                  }
                })
                // this.$common.wxCallBack(function () {
                //   wx.closeWindow()
                // })
              })
            } else {
              this.examineModel = true
              // this.$dialog.alert({
              //   message: this.language.successAlertNow[this.languageType]
              // }).then(() => {
              //   wx.closeWindow()
              // })
            }
            // this.$dialog.alert({
            //   message: '您的电子通行证已生成!'
            // }).then(() => {
            //   this.$router.push({
            //     name: 'epidemic-submit-success',
            //     query: {}
            //   })
            // })
          } else {
            this.successModel = false
            this.submitDisabled = false
            this.submitLoading = false
            this.failNotice(ret.data.errmsg + '/sid:/' + ret.data.sid)
          }
        })
      }
      if (this.addType === '1') {
        insertNewPermitPerson(this.formItem).then(ret => {
          if (ret.data.errcode === 0) {
            this.submitDisabled = true
            this.submitLoading = false
            console.log('保存回调', ret.data.data)
            window.localStorage.removeItem('formData')
            if (this.$route.query.selfTs === 'selfTs') {
              this.$dialog.alert({
                title: this.ld.frame.success.title[this.languageType],
                message: this.ld.frame.success.msg[this.languageType]
              }).then(() => {
                // this.$common.wxCallBack(function () {
                //   wx.closeWindow()
                // })
                this.$router.push({
                  name: 'epidemic-newly-added-waiji-list',
                  query: {
                    newlyAddedType: '1'
                  }
                })
              })
            } else {
              this.examineModel = true
              // this.$dialog.alert({
              //   message: this.language.successAlertNow[this.languageType]
              // }).then(() => {
              //   wx.closeWindow()
              // })
            }
            // this.$dialog.alert({
            //   message: '您的电子通行证已生成!'
            // }).then(() => {
            //   this.$router.push({
            //     name: 'epidemic-submit-success',
            //     query: {}
            //   })
            // })
          } else {
            this.successModel = false
            this.submitDisabled = false
            this.submitLoading = false
            this.failNotice(ret.data.errmsg + '/sid:/' + ret.data.sid)
          }
        })
      }
    },
    getOpenidInfoAction () {
      getOpenidMsg().then(ret => {
        console.log('判断是否注册过', ret.data)
        if (ret.data.errcode === 0) {
          if (!this.$common.xeUtils.isEmpty(ret.data.data.result)) {
            // this.successModel = true
            // this.$router.push({
            //  name: 'epidemic-submit-success',
            //  query: {}
            // })
            if (ret.data.data.result.type === '1') {
              this.$router.push({
                name: 'epidemic-submit-success-waiji',
                query: {}
              })
            } else {
              this.examineModel = true
              this.formItem.card_no = ret.data.data.result.card_no
              // this.$dialog.alert({
              //   message: this.language.successAlertNow[this.languageType]
              // }).then(() => {
              //   wx.closeWindow()
              // })
            }
          }
        } else {
          // this.failNotice(ret.data.errmsg)
        }
      })
    },
    // 去苹果机型白边
    bodyScrollTop () {
      winToTop()
      this.setStorage(this.formItem)
    },
    setStorage (formData) {
      window.localStorage.setItem('formData', JSON.stringify(formData))
    },
    choose () {
      this.showReadme = !this.tongyi
    },
    examineCloseAction () {
      // wx.closeWindow()
      this.$router.push({
        name: 'epidemic-newly-added-waiji-list',
        query: {
          newlyAddedType: '1'
        }
      })
    },
    languageChange (val) {
      switch (val) {
        case 'en':
          // 英语
          this.languageType = 0
          break
        case 'jp':
          // 日语
          this.languageType = 1
          break
        case 'ko':
          // 韩语
          this.languageType = 2
          break
        case 'tc':
          // 繁体中文
          this.languageType = 3
          break
      }
    },
    getNationalityListAction () {
      this.nationalityData = this.guojiData
      console.log(this.nationalityData, '国籍')
    },
    nationalityConfirm (val) {
      this.formItem.is_permanent_name = val.text
      this.formItem.is_permanent = val.id
      console.log(val, '有啥')
      this.showNationality = false
    }
  },
  mounted () {
    console.log('语言状态', this.languageType)
    // 获取路由信息
    this.routeObj = this.$route.query
    if (this.routeObj.type) {
      this.addType = this.$route.query.type
    }
    // console.log('表单页面路由信息', this.routeObj)
    // 获取登录信息
    if (this.routeObj.lang) {
      this.languageType = parseInt(this.routeObj.lang)
    }
    this.getNationalityListAction()
    // this.getOpenidInfoAction()
    // 获取本地表单数据
    if (window.localStorage.getItem('formData')) {
      this.formItem = JSON.parse(window.localStorage.getItem('formData'))
      console.log('表单页面表单数据', this.formItem)
      window.localStorage.removeItem('formData')
    }
    // 区域菜单数据预处理
    // console.log('表单信息', this.formItem)
  },
  watch: {
    formItem () {
      console.log('表单变化啦')
    }
  }
}
</script>

<style scoped>
    /deep/ .van-field__label {
        min-width: 5.625rem;
        margin-right: 10px;
        width: auto;
    }

    .mobile-verify-code {
        display: flex;
        justify-content: center;
        padding: 15px;
    }

    .success-code {
        display: flex;
        justify-content: center;
        padding: 5px 15px 10px;
    }

    .success-title {
        padding: 5px;
        text-align: center;
    }

    .van-radio {
        float: left;
        margin-right: 10px;
    }

    .van-popup /deep/ .van-ellipsis {
        font-size: 0.95rem;
    }

    .title {
        width: 100%;
        padding: 0.625rem 0.9375rem;
        font-size: 12px;
    }

    .action-item .van-cell__title {
        -webkit-box-flex: inherit;
        -webkit-flex: inherit;
        flex: inherit;
        width: 5.625rem;
    }

    .content {
        width: 100%;
        background-color: #F5F5F5;
        box-sizing: border-box;
        -webkit-box-sizing: border-box;
    }

    .content >>> .van-cell {
        margin: 0 2%;
        width: 96%;
        font-size: 12px;
    }

    .content >>> .van-dialog__content {
        padding: 10px;
        text-align: center;
    }

    .van-field__control {
        font-size: 12px;
    }

    .content >>> .van-cell__value .van-field__body .van-field__control {
        font-size: 12px;
    }

    .content >>> .van-cell__value {
        text-align: left;
    }

    .div-bot {
        margin: 10px;
    }

    .div-bot >>> .van-button--info {
        border: 1px solid #75ACDC;
    }

    .div-bot >>> .van-button {
        height: 2.5rem;
    }

    .city-card-common-btn {
        color: white;
        font-size: 12px;
        padding: 0;
        width: 100%;
        border-radius: 5px;
        text-align: center;
        background-color: #75ACDC;
    }

    .content >>> .van-cell__value {
        /*flex: inherit;*/
        font-size: 12px;
    }

    .content >>> .value-item .van-cell__value {
        width: 100%;
    }

    .van-action-sheet__cancel, .van-action-sheet__item {
        font-size: 12px;
    }

    .van-cell__value span {
        /*color: black;*/
    }

    .van-dropdown-menu {
        height: 25px;
    }

    .van-hairline--top-bottom::after {
        border-width: 0px 0px;
    }

    .chaochu >>> .van-cell__value {
        width: 100%;
    }

    .div1 >>> .van-cell__value {
        width: 100%;
    }

    .div2 >>> .van-cell__value {
        width: 100%;
    }

    .other-info .van-field__label.radio-item, .tou .van-field__label.radio-item {
        width: 8.625rem;
    }

    .suggest.van-cell.van-field span {
        width: 5rem;
    }

    .readme-popup {
        padding: 25px;
    }

    .readme-popup .readme-popup-title {
        text-align: center;
        color: red;
        font-weight: bold;
        text-decoration: underline;
    }

    .readme-popup p {
        margin: 5px 0 5px 0;
        font-size: 12px;
        text-indent: 25px
    }

    .readme-popup-btn {
        display: flex;
        justify-content: center;
        margin-top: 10px;
    }

    .readme-popup-btn-sm {
        width: 45%;
    }

    .tong-yi-box {
        font-size: 12px;
    }

    .tong-yi-box >>> .van-checkbox__icon {
        font-size: 15px;
    }

    .language-bar {
        font-size: 14px;
        text-align: center;
        color: gray;
    }

    .language-bar-mini {
        font-size: 12px;
        text-align: center;
        color: gray;
    }

    /*.content >>> .van-button--small{*/
    /*    padding: 0;*/
    /*}*/
</style>
